#include "epit.h"

void epit_init(uint32_t frac, uint32_t value)
{
    EPIT1->CR &= ~(0x3 << 24);
    EPIT1->CR |= (0x1 << 24);

    EPIT1->CR &= ~(0xFFF << 4);
    EPIT1->CR |= (frac << 4);

    EPIT1->CR |= (0x1 << 3);
    EPIT1->CR |= (0x1 << 2);
    EPIT1->CR |= (0x1 << 1);

    EPIT1->LR = value;
    EPIT1->CMPR = 0;

    GIC_EnableIRQ(EPIT1_IRQn);
    system_regiser_irqhandler(EPIT1_IRQn, epit_irqhandler, NULL);

    EPIT1->CR |= (0x1 << 0);
}

void epit_irqhandler(unsigned int giccIar, void* param)
{
    static uint8_t beep_state = 0;

    if(gpio_pin_read(GPIO1, 18) == 0)
    {
        beep_state = !beep_state;
        beep_switch(beep_state);
    }
    epit_disable();
    EPIT1->SR |= 0x1;
}

void epit_enable(void)
{
    EPIT1->CR |= (0x1 << 0);
}

void epit_disable(void)
{
    EPIT1->CR &= ~(0x1 << 0);
}